package com.wavehi.web;

import com.wavehi.pojo.User;
import com.wavehi.service.IUserService;
import com.wavehi.service.impl.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;


/**
 * @Author WaveHi
 * @Date 23/9/2021 上午 9:05
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Deal the upload of file.
 */
@WebServlet(urlPatterns = "/fileUpAndDown")
@MultipartConfig(maxFileSize = 5 * 1024 * 1024L, maxRequestSize = 5 * 1024 * 1024 * 1024L)
public class FileUpLoadAndDownLoadServlet extends BaseServlet {
    //获取业务层对象
    private IUserService ius= new UserServiceImpl();

    protected void base(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除会话域绑定的登录信息
        req.getSession().removeAttribute("user");
        //转发
        req.getRequestDispatcher("/page/user/user_login.jsp").forward(req, resp);

    }
    protected void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取文件名
        String filename = req.getParameter("filename");
        //获取相应的文件
        File file = new File(req.getServletContext().getRealPath("/static/image/register/") + filename);
        //向客户端回传文件
        String name = req.getHeader("User-Agent").contains("MSIE") ? URLEncoder.encode(filename,
                "UTF-8") : new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        //向客户端推荐文件的名字
        resp.setHeader("Content-Disposition", "attachment;filename=" + name);
        //回传指定的文件
        Files.copy(Paths.get(file.toURI()),resp.getOutputStream());
    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取所有文件名
        String dirPath = req.getServletContext().getRealPath("/static/image/register/");
        File file = new File(dirPath);
        String[] list = file.list();
        //绑定数据到请求域
        req.setAttribute("list", list);
        //获取请求转发对象
        RequestDispatcher dispatcher = req.getRequestDispatcher("/page/user/file_display.jsp");
        //转发
        dispatcher.forward(req, resp);
    }
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取注册信息
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        //验证注册信息
        boolean exists = false;
        exists = ius.userExist(username);
        if(exists) {
            //设置错误信息
            req.setAttribute("errorMsg", "Username have exist!");
            //获取请求转发对象
            RequestDispatcher dispatcher = req.getRequestDispatcher("/page/user/user_register.jsp");
            //转发
            dispatcher.forward(req, resp);
        } else {
            //获取头像文件
            Part userImage = req.getPart("userImage");
            //验证文件的类型
            boolean isImage = userImage.getContentType().contains("image");
            if(!isImage) {
                //设置错误信息
                req.setAttribute("errorMsg", "Please upload an image!");
                //获取请求转发对象
                RequestDispatcher dispatcher = req.getRequestDispatcher("/page/user/user_register.jsp");
                //转发
                dispatcher.forward(req, resp);
            }else {
                //获取头像文件的存储位置
                String dirPath = getServletContext().getRealPath("/static/image/register") + "/";
                String fileName = UUID.randomUUID()
                        + userImage.getSubmittedFileName().substring(userImage.getSubmittedFileName().lastIndexOf("."));
                String absolutePath = "static/image/register/";
                //将头像文件写入磁盘
                userImage.write(dirPath + fileName);
                //向数据库添加数据
                User user = new User(username, password, absolutePath + fileName);
                ius.addUser(user);
                User userGet = ius.getUser(username);
                //向会话对象绑定登录信息
                req.getSession().setAttribute("user", userGet);
                //获取请求转发对象
                RequestDispatcher dispatcher = req.getRequestDispatcher("/page/user/user_index.jsp");
                //转发
                dispatcher.forward(req, resp);
            }
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取登录信息
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        //验证登录信息
        boolean isCorrect = ius.userExist(username, password);
        if(isCorrect) {
            //向会话对象绑定登录信息
            User user = ius.getUser(username);
            req.getSession().setAttribute("user", user);
            //获取请求转发对象
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/page/user/user_index.jsp");
            //转发
            requestDispatcher.forward(req, resp);
        }else {
            //设置错误信息
            req.setAttribute("errorMsg", "Username or password is not right!");
            //获取请求转发对象
            RequestDispatcher dis = req.getRequestDispatcher("/page/user/user_login.jsp");
            //转发
            dis.forward(req, resp);
        }
    }
}
